if(typeof(trip) == 'undefined'){
	trip = {};
	trip.calculating = false;
}

trip.tips = {
			0:"Enter the values and click on calculate.",
			1:"You could enter either total amount spent by a person or you can enter ',' separated values in 'Money spent' field for a particular person.",
			2:"Person can be added and deleted from the table.",
			3:"The tool is used to calculate or distribute the money among people if people use a common acount for example: people go on a trip" +
			 		" and spend money togather and after an awesome trip people don't want to sit and do the calculations."+
			 		" Then this tool comes to rescue."
			};

 trip.validator = function(event){
	 var key = event.keyCode;
	 if ((key >= 48 && key <= 57 && !(event.shiftKey)) || ((key == 188)&& !(event.shiftKey))
			|| ((key == 190)&& !(event.shiftKey))){
		return true;
	}else{
		if(key!= 8 && key!= 9 && !(key >=37 && key<=40) ){
			event.preventDefault();
			return false;
		}
	}
};

trip.capitaliseFirstLetter = function(string){
	var name = "" , nameAr = string.trim().split(" ");
	for(var i=0;i<nameAr.length;i++){
		if(nameAr[i].length>=1){
			name += nameAr[i].charAt(0).toUpperCase() + nameAr[i].slice(1).toLowerCase()+" ";
		}
	}
    return name;
};

trip.calcTotalMoney = function(moneyStr){
	if(moneyStr === ""){
		return false;
	}
	var money = 0, moneyArray = moneyStr.split(","),temp;
	for(var i=0;i<moneyArray.length;i++){
		if(moneyArray[i].length>=1){
			if(isNaN(moneyArray[i])){
				return false;
			}
			temp = parseFloat(moneyArray[i],10);
			temp = temp.toFixed(2)*100;
			if(temp>9007199254740992){
				return false;
			}
			money += temp;
		}
	}
	return money;
};

trip.reset = function(flag){
	jQuery('#output div.total').css("display", "none");
	if(!flag){
		var m = Math.floor(Math.random()*4);
		jQuery('#output .rm').html("<p class='tips'>"+ "<span>Tips</span><br/>"+trip.tips[m]+"</p>");
	}
};

trip.calculator = function(tbody,counter){
	if(!trip.calculating){
		trip.reset(true);
		tbody = tbody[0];

		var data = [], totalMoney = 0, remaining = [], haveToReceive = [], listOfName = [];
		var i = 0, name, money, j = 0, k = 0, toBeGiven = 0, result = "", msg, to, from, transfer ,inputF;
		for (; i < counter; i++) {
			name = tbody.children[i].children[1].children[0].value;
			inputF = tbody.children[i].children[2].children[0];
			money = trip.calcTotalMoney(inputF.value);
			if (name === "") {
				alert("Please fill the value of name.");
				tbody.children[i].children[1].children[0].focus();
				return false;
			}
			if(money === "" || money === false){
				alert("Please enter the correct value for money.Value entered may be too large or invalid number.")
				inputF.focus();
				return false;
			}
			name = trip.capitaliseFirstLetter(name).trim();
			if (listOfName.indexOf(name) != -1) {
				alert("Please enter unique values of names. If same person has spent money more than one time, "
						+ "give ',' separated values in 'Money spent' field");
				return false;
			}
			listOfName[i] = name;
			data[i] = {
				'name' : name,
				'money' : money,
				'remain' : 0
			};
		}
		trip.calculating = true;
		jQuery('#output div.rm').html('<p>Calculating...</p>');
		for (i = 0; i < counter; i++) {
			totalMoney += parseInt(data[i]['money'], 10);
		}
		var avgMoney = parseInt((totalMoney / counter), 10);

		for (i = 0; i < data.length; i++) {
			data[i]['remain'] = data[i]['money'] - avgMoney;
			if (data[i]['money'] > avgMoney) {
				remaining[j++] = data[i];
				toBeGiven += data[i]['remain'];
			} else if (data[i]['money'] < avgMoney) {
				haveToReceive[k++] = data[i];
			}
		}
		remaining.sort(function(a, b) {
			return a['remain'] - b['remain'];
		});
		haveToReceive.sort(function(a, b) {
			return b['remain'] - a['remain'];
		});
		// console.log(toBeGiven+" "+remaining+" "+haveToReceive);
		for (i = 0, j = 0; i < remaining.length; i++) {
			var mo = remaining[i];
			if (toBeGiven == 0) {
				break;
			}
			while (mo['remain'] != 0 && j < haveToReceive.length) {
				if (mo['remain'] == -(haveToReceive[j]['remain'])) {
					// console.log(haveToReceive[j]['name']+' has to give
					// '+mo['remain']+" to "+mo['name']);
					from = haveToReceive[j]['name'];
					to = mo['name'];
					transfer = mo['remain'];
					toBeGiven -= mo['remain'];
					mo['remain'] = haveToReceive[j]['remain'] = 0;
					j++;
				} else if (mo['remain'] > -(haveToReceive[j]['remain'])) {
					// console.log(haveToReceive[j]['name']+' has to give
					// '+(-haveToReceive[j]['remain'])+" to "+mo['name']);
					msg = haveToReceive[j]['name'] + ' has to give '
							+ (-haveToReceive[j]['remain']) + " to "
							+ mo['name'];
					from = haveToReceive[j]['name'];
					to = mo['name'];
					transfer = (-haveToReceive[j]['remain']);
					mo['remain'] += haveToReceive[j]['remain'];
					toBeGiven += haveToReceive[j]['remain'];
					haveToReceive[j]['remain'] = 0;
					j++;
				} else {
					// console.log(haveToReceive[j]['name']+' has to give
					// '+mo['remain']+" to "+mo['name']);
					from = haveToReceive[j]['name'];
					to = mo['name'];
					transfer = mo['remain'];
					msg = haveToReceive[j]['name'] + ' has to give '
							+ mo['remain'] + " to " + mo['name'];
					haveToReceive[j]['remain'] += mo['remain'];
					toBeGiven -= mo['remain'];
					mo['remain'] = 0;
				}
				transfer /= 100;
				msg = "<span>"+from + "</span> has to give <span>" + transfer + "</span> bucks to <span>" + to+"</span>";
				result += "<p>" + msg + ".</p>";
			}

		}
		totalMoney /= 100;
		avgMoney /= 100;
		if (result.length === 0
				&& (remaining.length === 0 || haveToReceive.length == 0)) {
			result = "<p>Nobody has to give anything, it's all set!!</p>";
		}
		window.setTimeout(function() {
			jQuery('#output div.total').css("display", "block");
			jQuery('#output div.total p:nth-child(1)').html("Total : " + totalMoney);
			jQuery('#output div.total p:nth-child(2)').html("Per head : " + avgMoney);
			jQuery('#output .rm').html(result);
			trip.calculating = false;
			$('html, body').animate({
			    scrollTop: $("#output").offset().top,
			    scrollLeft: $("#output").offset().left
			});
		}, 200);
	}
};

jQuery(document).ready(function(){
	var counter=0;
	var tbody = jQuery("#people tbody");
	var i;
	var first = "<tr><td><input type='checkbox' unchecked />" ,
		second ="</td><td><input placeholder='Name' type='text'/></td><td><input type='text' placeholder='Money spent' class='number'/></td></tr>"; 
	for(i=counter;i<2;i++){
		var str = first+second;
		tbody.append(str);
		counter++;
	}
	
	var checkselected = function(e){
		if(this.checked){
			jQuery(this.parentNode.parentNode).addClass('selectedrow');
		}else{
			jQuery(this.parentNode.parentNode).removeClass('selectedrow');
		}
	};
	
	var addRow = function(e){
		var str = first+second;
		tbody.append(str);
		jQuery(tbody[0].children[counter].children[2].children[0]).keydown(trip.validator);
		jQuery(tbody[0].children[counter].children[0].children[0]).click(checkselected);
		counter++;
	};
	
	var deleteRow = function(e){
		var selectedRows = jQuery("#people tr.selectedrow");
		if(selectedRows.length == 0){
			alert('No row selected.');
		}else if((tbody[0].children.length -selectedRows.length) < 2){
			alert("Atleast two rows should be there");
		}else{
			for(var i=0;i<selectedRows.length;i++){
				tbody[0].removeChild(selectedRows[i]);
				counter--;
			}
		}
	};
	
	jQuery("#addrow").click(function(){
		addRow();
		//jQuery("input.number").keypress(trip.validator);
	});	
	
	jQuery("#delete").click(deleteRow);
	
	jQuery("input.number").keydown(trip.validator);
	
	jQuery("td input:checkbox").click(checkselected);
	
	jQuery("#calculate").click(function(){
		trip.calculator(tbody,counter);
	});	
	
	jQuery("#cancel").click(function(){
		window.location.reload();
	});
	trip.reset();
});

